#include <iostream>
#include <unistd.h>
#include <pthread.h>
#define N 5
using namespace std;
int ticket = 1000;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void* pthreadRun(void* arg){
    char* name = static_cast<char*>(arg);
    int sum = 0;
    while(true){
        pthread_mutex_lock(&mtx);
        if(ticket>0){
            usleep(2000);
            --ticket;
            cout<<"线程:"<<name<<"抢票成功！"<<"剩余："<<ticket<<"票"<<endl;
            sum++;
            pthread_mutex_unlock(&mtx);
        }else{
            pthread_mutex_unlock(&mtx);
            break;
        }
    }
    cout<<name<<"抢了"<<sum<<"张票"<<endl;
    delete[] name;
    return nullptr;
}

int main()
{
    pthread_t pths[N];
    for(int i = 1;i<=N;++i){
        char* name = new char[64];
        snprintf(name,64,"pthread-%d",i);
        pthread_create(&pths[i-1],nullptr,pthreadRun,name);
    }
    for(int i = 1;i<=N;++i){
        int ret = pthread_join(pths[i-1],nullptr);
        if(ret!=0){
            perror("线程等待失败！");
            return 1;
        }
    }
    cout<<"线程全部退出完毕"<<"剩余票数:"<<ticket<<endl;

    return 0;
}